import re
from datetime import datetime, timedelta


class LogInfoFetch:
    def get_info(self, *args, **kwargs):
        # 匹配规则
        match_rule = re.compile(
            r'(?P<ip>.*?)- - \[(?P<times>.*?)\] "(?P<request>.*?)" (?P<status>.*?) (?P<bytes>.*?) "(?P<referer>.*?)" "('
            r'?P<ua>.*?)"')
        result = match_rule.match(*args, **kwargs)
        ip = result.group("ip")  # 匹配ip
        status = result.group("status")  # 匹配状态码
        times = result.group("times")  # 匹配时间
        times = times.replace(" +0000", "")  # 替换+0000为空
        # times = datetime.strptime(times, "%d/%b/%Y:%H:%M:%S")  # 将时间格式化成友好的格式
        # times = times + timedelta(hours=8)  # 在原有时间上 +8小时
        request = result.group("request").split()  # request处理
        request_method = request[0]  # get or post
        request_url = request[1]  # /index.php
        request_protocol = request[2]  # HTTP/1.1
        ua = result.group("ua")  # user_agent处理
        if "Windows" in ua:
            user_agent = "windows"
        elif "iPad" in ua:
            user_agent = "ipad"
        elif "Android" in ua:
            user_agent = "android"
        elif "Macintosh" in ua:
            user_agent = "mac"
        elif "iPhone" in ua:
            user_agent = "iphone"
        else:
            user_agent = "unknown"
        info = dict(
            ip=ip,
            status=status,
            time=(datetime.strptime(times, "%d/%b/%Y:%H:%M:%S")+timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
            method=request_method,
            path=request_url,
            protocol=request_protocol,
            user_agent=user_agent
        )
        return info


if __name__ == '__main__':
    lgf = LogInfoFetch()
    str = '118.116.107.72 - - [23/Jul/2022:12:34:40 +0000] "GET /index.php HTTP/1.1" 200 69003 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.62" "-"'
    print(lgf.get_info(str))
